package portal.monitor.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import beans.HttpResultList;
import net.sf.json.JSONObject;
import portal.common.ResultData;
import portal.monitor.dao.MonitorHost;
import portal.monitor.dao.MonitorHostGroup;
import portal.monitor.dao.MonitorRelated;
import portal.monitor.dao.service.MonitorHostGroupService;
import portal.monitor.dao.service.MonitorHostService;
import portal.monitor.dao.service.MonitorRelatedService;
import portal.monitor.service.HostCtrlService;
import portal.monitor.service.ModeRecordService;

@RestController
public class MonitorHostServlet extends HttpServlet {
    @Autowired
    MonitorHostService monitorHostService;
    @Autowired
    MonitorRelatedService monitorRelatedService;
    private HttpResultList result;
    @Autowired
    MonitorHostGroupService monitorHostGroupService;
    @Autowired
    ModeRecordService modeRecordService;
    @Autowired
    HostCtrlService hostCtrlService;
    

    @RequestMapping(value = "/MonitorHostServlet", method = RequestMethod.POST)
    public void HostService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType) {
                case "add":
                    addHost(request);
                    break;
                case "delete":
                    deleteHost(request);
                    break;
                case "deletes":
                    deleteHosts(request);
                    break;
                case "alter":
                    alterHost(request);
                    break;
                case "showAll":
                    showAll();
                    break;
                case "showPaged":
                    showPaged(request);
                    break;
                case "showDetail":
                    showDetail(request);
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
            response.getWriter().print(JSONObject.fromObject(result).toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());
    }

    private void addHost(HttpServletRequest request) {
        String hostName = request.getParameter("hostName");
        String hostIp = request.getParameter("hostIp");
        String hostMac = request.getParameter("hostMac");
        String introduction = request.getParameter("introduction");
        String[] hostGroups = request.getParameter("hostGroup").split(",");
        
        //添加mac地址
       if(StringUtils.isEmpty(hostMac)){
    	   hostMac = getMac(hostIp);
       }
        
        MonitorHost monitorHost = new MonitorHost(hostName, hostIp, hostMac, introduction);
        boolean res = monitorHostService.insert(monitorHost) == 1;
        if(res){
            for(String hostGroup: hostGroups){
            	MonitorRelated monitorRelated = null;
            	if(hostGroup.length()>0){
            		 monitorRelated = new MonitorRelated(monitorHost.getHostId(), Integer.parseInt(hostGroup));
            		 res = res & monitorRelatedService.insert(monitorRelated) == 1;
            	}else{
            		//  monitorRelated = new MonitorRelated(monitorHost.getHostId());
            	}
            	 
            }
            result.setResult(res);
        }else {
            result.setResult(false);
        }
    }

    private void deleteHost(HttpServletRequest request) {
        Integer hostId = Integer.parseInt(request.getParameter("hostId"));
        boolean res = monitorHostService.deleteByPrimaryKey(hostId) == 1;
        result.setResult(res);
    }
    private void deleteHosts(HttpServletRequest request) {
        String[] temp = request.getParameter("hostIds").split(",");
        Integer[] hostIds = new Integer[temp.length];
        for (int i = 0; i < temp.length; i++) {
            hostIds[i] = Integer.parseInt(temp[i]);
        }
        monitorHostService.deleteByPrimaryKeys(hostIds);
        monitorRelatedService.deleteByHostId(hostIds);
        result.setResult(true);
    }

    private void alterHost(HttpServletRequest request) {
        Integer hostId = Integer.parseInt(request.getParameter("hostId"));
        String hostName = request.getParameter("hostName");
        String hostIp = request.getParameter("hostIp");
        String hostMac = request.getParameter("hostMac");
        String introduction = request.getParameter("introduction");
        String[] hostGroups = request.getParameter("hostGroup").split(",");
        //添加mac地址
        if(StringUtils.isEmpty(hostMac)){
     	   hostMac = getMac(hostIp);
        }
        MonitorHost monitorHost = new MonitorHost(hostId, hostName, hostIp, hostMac, introduction);
        boolean res = monitorHostService.updateByPrimaryKey(monitorHost) == 1;
        monitorRelatedService.deleteByHostId(hostId);
        for(String hostGroup: hostGroups){
            MonitorRelated monitorRelated = new MonitorRelated(hostId, Integer.parseInt(hostGroup));
            res = res & monitorRelatedService.insert(monitorRelated) == 1;
        }
        result.setResult(res);
    }

    private void showAll() {
        List<MonitorHost> hostList = monitorHostService.selectAll();
        for(MonitorHost monitorHost:hostList){
            List<MonitorRelated> relatedList = monitorRelatedService.selectByHostId(monitorHost.getHostId());
            StringBuilder hostGroupIds = new StringBuilder();
            if(relatedList.size()>0) {
                for (MonitorRelated monitorRelated : relatedList) {
                	hostGroupIds.append(",");
                    hostGroupIds.append(String.valueOf(monitorRelated.getHostGroupId()));
                }
                hostGroupIds.deleteCharAt(0);
            }
            Set<String> set = modeRecordService.getRecord(monitorHost.getHostName());
            if(set.size()>0){
            	 monitorHost.setModeName(set.toString());
            }
            monitorHost.setHostGroupIds(hostGroupIds.toString());
        }
        List<Object> objects = new ArrayList<Object>(hostList);
        result.setResult(objects.size() > 0);
        result.setDatas(objects);
    }

    private void showPaged(HttpServletRequest request) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        List<MonitorHost> hostList = monitorHostService.selectByPage(currentPage, onePageCount);
        for(MonitorHost monitorHost:hostList){
            List<MonitorRelated> relatedList = monitorRelatedService.selectByHostId(monitorHost.getHostId());
            StringBuilder hostGroupIds = new StringBuilder();
            if(relatedList.size()>0) {
                for (MonitorRelated monitorRelated : relatedList) {
                    /*hostGroupIds.append(",");
                    hostGroupIds.append(String.valueOf(monitorRelated.getHostGroupId()));*/
                	 hostGroupIds.append(",");
                	if(monitorRelated==null){
                		continue;
                	}
                	MonitorHostGroup group= monitorHostGroupService.selectByPrimaryKey(monitorRelated.getHostGroupId());
                   
                    hostGroupIds.append(group.getHostGroupName());
                }
                hostGroupIds.deleteCharAt(0);
            }
            
            monitorHost.setHostGroupIds(hostGroupIds.toString());
        }
        List<Object> objects = new ArrayList<Object>(hostList);
        int pageNum = monitorHostService.pageNum(onePageCount);
        result.setResult(objects.size() > 0);
        result.setMessage(pageNum + "");
        result.setDatas(objects);
    }

    private void showDetail(HttpServletRequest request) {
        Integer hostId = Integer.parseInt(request.getParameter("hostId"));
        MonitorHost monitorHost= monitorHostService.selectByPrimaryKey(hostId);
        List<Object> objects = new ArrayList<>();
        objects.add(monitorHost);
        result.setResult(monitorHost != null);
        result.setDatas(objects);
    }
    
    private String getMac(String hostIp){
    	  ResultData rd = new ResultData();
   	   rd =hostCtrlService.execCmd(hostIp, "mac");
   	   String hostMac = (String) rd.data;
    	return hostMac;
    }
}
